package org.example;

/**
 * <b>MyRunnable.java</b></br>
 *
 * <pre>
 *  实现Runnable创建线程
 * </pre>
 *
 * @author zhoulihao xiaogezhou929@163.com
 * @date 2021年06月05日 14:29:50
 * @since JDK 1.8
 */
public class MyRunnable implements  Runnable {
    private Thread thread;
    private String name;

    public MyRunnable(String name){
        this.name=name;
        System.out.println("Runnable创建线程"+name);
    }
    @Override
    public void run() {
        for (int i = 0; i < 3; i++) {
            System.out.println("运行线程 " + name + " " + i);
            // 线程休眠，增强线程交互执行的效果
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("\r\n退出线程 " + name);
    }
    /**
      * <b>start</b> <br/>
      * <br/>
      * 因为实现runnable接口需要一个传递当前对象给Thread的构造函数，然后使用Thread对象调用start()创建线程,this是当前对象，name是构造函数中传入进来的值
      * <br/>
      *
      * @author zhoulihao xiaogezhou929@163.com
      * @param
      * @return void
      *
      */
    public  void start(){
        System.out.println("启动线程");
        if(thread==null){
            thread=new Thread(this,name);
            thread.start();
        }
    }

}
